package arithmetic;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * 股票的最佳买卖时机：事后诸葛亮，在价格出来之后，看如何操作收益最大化
 *
 * @author gaojie
 * @date 2022-03-11
 */
public class MaxProfit {

    @Test
    void test() {
        assert fun(new int[]{1, 2, 3, 4, 5}) == 4;
        assert fun(new int[]{7, 6, 4, 3, 1}) == 0;
        assert fun(new int[]{7, 1, 5, 3, 6, 4}) == 7;
        assert fun(new int[]{1, 9, 6, 9, 1, 7, 1, 1, 5, 9, 9, 9}) == 25;
    }

    int profits, min, max;

    /**
     * 1.记录最低价、最高价、总收益
     * 2.遍历价格数组
     * 2.1.若价格低于最高价，则卖出，然后更新最高价和最低价
     * 2.2.若价格高于最高价，则更新最高价，若为最后一天，也要卖出
     */
    int fun(int[] prices) {
        System.err.println(Arrays.toString(Arrays.stream(prices).toArray()));
        int length = prices.length;
        profits = 0;
        min = max = prices[0];
        for (int i = 1; i < length; i++) {
            int price = prices[i];
            if (price < max) {
                sale();
                max = min = price;
            } else {
                if (price > max) max = price;
                if (i == length - 1) sale();
            }
        }
        return profits;
    }

    /**
     * 卖出
     * 1.判断是否有利润
     * 2.有利润则卖出，统计收益
     */
    void sale() {
        if (min != max) {
            int profit = max - min;
            profits += profit;
            System.out.printf("买入价: %d, 卖出价: %d, 本次收益：%d, 总收益: %d%n", min, max, profit, profits);
        }
    }

}
